package com.demo.thread;

import com.sun.activation.registries.LogSupport;

import java.util.concurrent.locks.LockSupport;

/**
 * 线程执行顺序问题
 */
public class ThreadExecutionOrderQuestion {

    private  static  void threadloop() throws  InterruptedException{
        Thread t1 = new Thread(ThreadExecutionOrderQuestion::action,"t1");
        Thread t2 = new Thread(ThreadExecutionOrderQuestion::action,"t2");
        Thread t3 = new Thread(ThreadExecutionOrderQuestion::action,"t3");
        t1.start();
        while (t1.isAlive()){
            //自旋
        }
        t2.start();
        while (t2.isAlive()){
            //自旋
        }
        t3.start();
        while (t3.isAlive()){
            //自旋
        }
    }

    private  static  void threadwait() throws  InterruptedException{
        Thread t1 = new Thread(ThreadExecutionOrderQuestion::action,"t1");
        Thread t2 = new Thread(ThreadExecutionOrderQuestion::action,"t2");
        Thread t3 = new Thread(ThreadExecutionOrderQuestion::action,"t3");
        doStartAndWait(t1);
        doStartAndWait(t2);
        doStartAndWait(t3);
    }

    private static  void doStartAndWait(Thread thread){
        if(Thread.State.NEW.equals(thread.getState())){
            thread.start();
        }
        //其实是活着的就咨询等待了。线程完了。
        while (thread.isAlive()){
            synchronized (thread){
                try {
                    thread.wait();//到底是谁通知到这个wait方式了。
                    //LockSupport.park(); 不能使用这个。线程会堵塞，必须通过Locksupport.unpark去唤醒。
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 通过join 的方式来控制线程执行顺序
     * @throws InterruptedException
     */
    private  static  void threadjoinOneByOne() throws  InterruptedException{
        Thread t1 = new Thread(ThreadExecutionOrderQuestion::action,"t1");
        Thread t2 = new Thread(ThreadExecutionOrderQuestion::action,"t2");
        Thread t3 = new Thread(ThreadExecutionOrderQuestion::action,"t3");

        t1.start();
        t1.join();//等子线程运行完了，调用的线程才能继续往下走

        t2.start();
        t2.join();
        t3.start();
        t3.join();
    }

    public static void main(String[] args) throws  InterruptedException {
        threadwait();
    }

    private static void action(){
        System.out.printf("线程%s在运行......%n",Thread.currentThread().getName());
    }
}
